/***
  author: sailing
  date: 2017/7/29
**/
import axios from 'axios'
import tools from './tools'
import dataC from './data'
import eventBus from '../eventBus'

function create (obj) {
  return {
    data: {
      obj: obj['label'],
      source: obj['source'],
      target: obj['target'],
      e_port: obj['e_port'],
      s_port: obj['s_port']
    }
  }
}

function getNextLine (arr, id) {
  for (var i=0; i<arr.length; i++) {
    if (arr[i]['line']['id'] !== id) return arr[i]
  }
}

function CreateLine (node, lineArr, sNode, lineId) {
  if (node.type !== 'distributing_cabinet' && sNode) {
    // console.log('node type:', node)
    var obj = {
      source: sNode.id,
      target: node.id
    }
    lineArr.push(create(obj))
    return
  }
  var lineObjArr = tools.findLine(node.id)
  var nextId = ''
  if (!lineObjArr) return

  if (!lineId) {
    nextId = lineObjArr[0]['nextId']
  } else {
    var objLine = getNextLine(lineObjArr, lineId)
    nextId = objLine['nextId']
    lineId = objLine['line']['id']
  }

  if (!sNode) sNode = node
  
  var nodeT = tools.findNode(nextId)
  CreateLine(nodeT, lineArr, sNode, lineId)
}

export default {
  findAndCreateLine () {
    var lineArr = []
    dataC.cy.edges(function (i, edge) {
      dataC.cy.remove(edge)
    })
   
    for (var i=0; i<dataC.nodes.length; i++) {
      var nodeData = dataC.nodes[i]
      if (nodeData['data']['type'] !== 'distributing_cabinet' && nodeData['data']['type'] !== 'switch') {
        CreateLine(nodeData['data'], lineArr)
      }
      // CreateLine(nodeData['data'])
    }
    console.log('lineArr', lineArr)
    /*
    this.cy.edges(function (i, edge) {
      that.cy.remove(edge)
    })
    */
    dataC.cy.nodes(function (i, node) {
      var nodeD = node.data()
      console.log('nodeD:', nodeD)
      if (nodeD['type'] === 'distributing_cabinet') {
        dataC.cy.remove(node)
      }
      // that.cy.remove(node)
    })
    
    for (var j=0; j<lineArr.length; j++) {
      dataC.cy.add(lineArr[j])
    }  
  }
}
